<?php

/**
 * @author jrodriguez
 * @copyright 2013
 */
require_once("../../PathHelper.php");
require_once $rootPath.'Gazzetta.DAL/MysqlConnection.php';
require_once $rootPath.'Gazzetta.DAL/DBConnectionHelper.php';
abstract class BaseRepository
{
    protected $connection;
    protected $tableName;
    
    public function getById($id)
    {
        $conn = $this->buildConnection();
        $result = $conn->getResultSet("SELECT * FROM $this->tableName WHERE id = $id");
        
        foreach (new LimitIterator($result, 0, 1) as $row)
        {       
            return $this->formatOne($row);        
        }       
    }
    
    function getBaseSelectQuery()
    {
    	return "SELECT * FROM $this->tableName";
    }
    
    public function all()
    {
        $conn = $this->buildConnection();
        $result = $conn->getResultSet($this->getBaseSelectQuery());
        return $this->formatCollection($result);
    }
    
    abstract protected function formatOne($row);
    
    public function formatCollection($result)
    {
        $entityArray = array();
        
        foreach ($result as $row) 
        {
            $entityArray[] = $this->formatOne($row);           
        }
        return $entityArray;
    }
    
    public function getWithWhere($where)
    {
    	$conn = $this->buildConnection();
    	$result = $conn->getResultSet($this->getBaseSelectQuery().' '.$where);
    	return $this->formatCollection($result);
    }
    
    protected function buildConnection()
    {
        return new MysqlConnection(DBConnectionHelper::$SERVER , DBConnectionHelper::$USERNAME, DBConnectionHelper::$USERPASS, DBConnectionHelper::$DATABASE);
    }
    
    public function add(BaseEntity $entity)
    {
        $conn = $this->buildConnection();
        $sql = 'INSERT INTO ' . $this->tableName . ' ' . $this->buildValuesSentence($entity);
        $result = $conn->getResultSet($sql);
    }
    
    protected function buildValuesSentence(BaseEntity $entity)
    {
        return '(' . $this->buildColumnsPartForInsert(). ') VALUES ('.$this->buildValuesPartForInsert($entity) . ');';
    }
    
    protected function buildColumnsPartForInsert()
    {
        
    }
    protected function buildValuesPartForInsert($entity)
    {
        
    }
	
	public function delete($id)
	{
		$conn = $this->buildConnection();
        $sql = 'DELETE FROM ' . $this->tableName . ' WHERE Id = ' . $id;
        $result = $conn->getResultSet($sql);
	}
	
	public function update(BaseEntity $entity)
	{
		$conn = $this->buildConnection();
        $sql = 'UPDATE ' . $this->tableName . ' SET ' . $this->buildSetSentence($entity) . ' WHERE Id = ' . $entity->getId();
        $result = $conn->getResultSet($sql);
	}
	 protected function buildSetSentence($entity)
    {
        
    }
}

?>